﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Ysb.Components;
using BLL;
using Model;
using System.Xml;
public partial class Admin_BillEdit : System.Web.UI.Page
{
    public string Mg;
    public string NotMg;
    public string IsMg;
    public string BaozhuangFL;
    public string DaigouFl;
    //默认绑定客户
    public string dfcreateuser;
    public string dIsMg;
    public string dBaozhuangFL;
    public string dDaigouFl;

    public string accnb;

    Tools tool = new Tools();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!AdminCheck.Check(this, 1))
        {
            Response.Redirect(AdminCheck.RedirectPage);
            return;
        }

        if (!Page.IsPostBack)
        {
            ViewState["lasturl"] = Request.UrlReferrer.ToString();

            XmlDocument Document = new XmlDocument();
            Document.Load(ApplicationInfo.PhysicalApplicationPath + "Config/AppConfig.config");
            Mg = Document.GetElementsByTagName("set1").Item(0).Attributes["value"].Value;
            NotMg = Document.GetElementsByTagName("set2").Item(0).Attributes["value"].Value;
            BindDDL();
            
            if (Request.QueryString["area"] != null)
            {


                dataLoad();
            }
            else
            {
              BindGSUser(true);
			
            }
            Rpt_Name.DataSource = new PublicSqlService().GetData("GoodsName", "Tbl_SplitBillGoods", "");
            Rpt_Name.DataBind();

        }
    }


  

    //重用
    void dataLoad()
    {

        accnogs.SelectedIndex = 1;
        DataTable dt = new PublicSqlService().GetData("ChargedWt,FreightCharge,DeclarePrice,DimensionsWeight,CreateUserID,AccountNo,Sender,FromPhoneNo,FromCompany,FromAddress,Receiver,ToPhoneNo,ToCompany,ToAddress,TotalWeight,DimensionsH,DimensionsL,DimensionsW,namepy,companynamepy,website,tozipcode,TrackingNo,Destination", "Tbl_WayBill", "TrackingNo='" + Request.QueryString["tno"].ToString() + "'");
        if (dt.Rows.Count != 1)
        {
            Jscript.AlertAndGoBack("单据 数据异常！请记录单号联系管理人员！");
            return;
        }

        GetUser(dt.Rows[0]["CreateUserID"].ToString());//人员绑定
        BindGSUser(false);
        #region   发送人基本属性
        gs_txt.Value = dt.Rows[0]["AccountNo"].ToString();
        sendertxt.Value = dt.Rows[0]["Sender"].ToString();

        phonenotxt.Value = dt.Rows[0]["FromPhoneNo"].ToString();
        companytxt.Value = dt.Rows[0]["FromCompany"].ToString();
        addtxt.Value = dt.Rows[0]["FromAddress"].ToString();
        //dt.Rows[0]["FromCity"].ToString(); "");
        // dt.Rows[0]["FromState"].ToString(); "");
        // dt.Rows[0]["FromZIPCode"].ToString(); "");
        #endregion
        #region   收件人基本属性
        renametxt.Value = dt.Rows[0]["Receiver"].ToString();
        rephonenotxt.Value = dt.Rows[0]["ToPhoneNo"].ToString();
        recompanytxt.Value = dt.Rows[0]["ToCompany"].ToString();
        readdtxt.Value = dt.Rows[0]["ToAddress"].ToString();
        #endregion
        zhongliang_txt.Value = dt.Rows[0]["TotalWeight"].ToString();//重重量
        gaotxt.Value = dt.Rows[0]["DimensionsH"].ToString();
        changtxt.Value = dt.Rows[0]["DimensionsL"].ToString();
        kuantxt.Value = dt.Rows[0]["DimensionsW"].ToString();
        tijizhonglianghd.Value = dt.Rows[0]["DimensionsWeight"].ToString();
        haiguanall.Text = dt.Rows[0]["DeclarePrice"].ToString(); //海关申报总价
        haiguanhd.Value = dt.Rows[0]["DeclarePrice"].ToString();

        ChargedWt.Text = dt.Rows[0]["ChargedWt"].ToString(); //收费重量
        shoufeizhonglianghd.Value = dt.Rows[0]["ChargedWt"].ToString();
        FreightChargelb.Text = dt.Rows[0]["FreightCharge"].ToString();  //重量收费
        zlshoufeihd.Value = dt.Rows[0]["FreightCharge"].ToString();
		namepy.Value = dt.Rows[0]["namepy"].ToString();//add
	 companynamepy.Value = dt.Rows[0]["companynamepy"].ToString();//add
	    website.Value = dt.Rows[0]["website"].ToString();//add
		tozipcode.Value = dt.Rows[0]["tozipcode"].ToString();//add
		  TrackingNo.Value = dt.Rows[0]["TrackingNo"].ToString();//add
		          mdd_ddr.Text = dt.Rows[0]["Destination"].ToString();


        dianfufeilb.Value = "0";//垫付费

        daigoufeilb.Text = "0"; //代购费

        daigoufeihd.Value = "0";
        baozhuangfeilb.Text = "0"; //包装费
        baozhuangfeihd.Value = "0";
        guanshuitxt.Value = "0";  //关税
        baoxianfeitxt.Value = "0";//保险费
        othertxt.Value = "0";//其他费用
        youhuitxt.Value = "0";  //优惠
        Totallb.Text = "0";  //总费用
        Totalhb.Value = "0";


        BindHuoWu(Request.QueryString["tno"].ToString());
    }

    void BindHuoWu(string NO)
    {


        DataTable dt = new PublicSqlService().GetData("*", "TblShipment", "TrackingNo='" + NO.Trim() + "'");

        if (dt.Rows.Count > 0)
        {


            if (dt.Rows.Count == 1)
            {
                name1.Value = dt.Rows[0]["Commodity"].ToString();
                num1.Value = dt.Rows[0]["Qty"].ToString();
                price1.Value = dt.Rows[0]["ValueForCustoms"].ToString();


            }
            if (dt.Rows.Count > 1)
            {
                name1.Value = dt.Rows[0]["Commodity"].ToString();
                num1.Value = dt.Rows[0]["Qty"].ToString();
                price1.Value = dt.Rows[0]["ValueForCustoms"].ToString();
                name2.Value = dt.Rows[1]["Commodity"].ToString();
                num2.Value = dt.Rows[1]["Qty"].ToString();
                price2.Value = dt.Rows[1]["ValueForCustoms"].ToString();
            }

        }

    }


    void GetUser(string id)
    {



        DataTable dt = new PublicSqlService().GetData("AccountNo,TrueName,Tel,Company,Address,Country", "TblUserInfo", "Uid=" + id);
        if (dt.Rows.Count == 0)
        {
            Tools.OpenWindow(this, "公司信息异常，请联系管理人员");
            return;
        }
        //    accnb = dt.Rows[0]["AccountNo"].ToString();
        anccnum.Value = dt.Rows[0]["AccountNo"].ToString();
        sendertxt.Value = dt.Rows[0]["TrueName"].ToString();
        phonenotxt.Value = dt.Rows[0]["Tel"].ToString();
        companytxt.Value = dt.Rows[0]["Company"].ToString();
        addtxt.Value = dt.Rows[0]["Address"].ToString();
        creaduser.Value = id;
        if (dt.Rows[0]["Country"].ToString().Trim() == "美国")
        {
            IsMg = "true";
        }
        else
        {
            IsMg = "false";
        }
        DataTable ndt = new PublicSqlService().GetData("PackagingRate,ShoppingServiceRate", "Tb_UserProperty", "UserID=" + id);

        BaozhuangFL = ndt.Rows[0]["PackagingRate"].ToString();
        DaigouFl = ndt.Rows[0]["ShoppingServiceRate"].ToString();


    }

    /// <summary>
    ///  //绑定公司用户
    /// </summary>
    /// <param name="ok">如果是全部绑定为true f否则flaw</param>
    void BindGSUser(bool ok)
    {
        dfcreateuser = "847";
        DataTable dt = new PublicSqlService().GetData("AccountNo,TrueName,Tel,Company,Address,Country", "TblUserInfo", "Uid=847");
        if (dt.Rows.Count == 0)
        {
           Jscript.AlertAndGoBack("单据 数据异常！请记录单号联系管理人员！");
            return;
        }
        accnb = dt.Rows[0]["AccountNo"].ToString();




        sendertxt.Value = dt.Rows[0]["TrueName"].ToString();
        phonenotxt.Value = dt.Rows[0]["Tel"].ToString();
        companytxt.Value = dt.Rows[0]["Company"].ToString();
        addtxt.Value = dt.Rows[0]["Address"].ToString();
        if (ok)
        {
            creaduser.Value = "847";
            anccnum.Value = dt.Rows[0]["AccountNo"].ToString();
        }



        if (dt.Rows[0]["Country"].ToString().Trim() == "美国")
        {

            dIsMg = "true";
            if (ok)
            {
                IsMg = "true";
            }
        }
        else
        {
            dIsMg = "false";

            if (ok)
            {
                IsMg = "false";
            }
        }
        DataTable ndt = new PublicSqlService().GetData("PackagingRate,ShoppingServiceRate", "Tb_UserProperty", "UserID=1");

        dBaozhuangFL = ndt.Rows[0]["PackagingRate"].ToString();
        dDaigouFl = ndt.Rows[0]["ShoppingServiceRate"].ToString();
        if (ok)
        {
            BaozhuangFL = ndt.Rows[0]["PackagingRate"].ToString();
            DaigouFl = ndt.Rows[0]["ShoppingServiceRate"].ToString();
        }
    }
    //起运地 目的地
    void BindDDL()
    {
        qyd_ddr.DataSource = new PlaceService().GetStart();
        qyd_ddr.DataTextField = "PlaceName";
        qyd_ddr.DataBind();
       // qyd_ddr.Items.Insert(0, "");
        mdd_ddr.DataSource = new PlaceService().GetEnd();
        mdd_ddr.DataTextField = "PlaceName";
        mdd_ddr.DataBind();

     //   mdd_ddr.Items.Insert(0, "");
      //  jifeitype.DataSource = new PayModelService().GetCalType();

		DataTable table1 = new PayModelService().GetCalType();
		table1.Columns.Add("bbb", System.Type.GetType("System.String"), "name+'-'+Substring(cid,3,10)"); 
		jifeitype.DataSource = table1;
		
        jifeitype.DataTextField = "bbb";
        jifeitype.DataValueField = "cid";
        jifeitype.DataBind();

        statelistdrr.DataSource = new BillStateService().GetAllList();
        statelistdrr.DataTextField = "Description";
        statelistdrr.DataValueField = "BSID";
        statelistdrr.DataBind();
        cplistdrr.DataSource = new DomesticShippingService().GetAll();
        cplistdrr.DataTextField = "CompanyName";
        cplistdrr.DataValueField = "ID";
        cplistdrr.DataBind();
        cplistdrr.Items.Insert(0, new ListItem("", "0"));

        paylist.DataSource = new PayModelService().GetAll();
        paylist.DataTextField = "ModelName";
        paylist.DataValueField = "PID";
        paylist.DataBind();
        paylist.SelectedIndex = 1;

    }
	
	
	 #region 获取写入编辑
    private void InsertHuowu2(string acc)
    {

        //写入


        new PublicSqlService().Del("TblShipment", "TrackingNo='" + acc.Trim() + "'");
        Shipment sp = new Shipment();
        sp.Commodity = name1.Value;
        sp.TrackingNo = acc;
        if (sp.Commodity.Trim() != "")
        {
            sp.HarmonizedCode = "";
            sp.PostTime = DateTime.Now;
            sp.Qty = new Tools().StringToIntDif(num1.Value);
            sp.UnitValue = 0;
            sp.ValueForCustoms = new Tools().StringToDecimalDif(price1.Value);

            new ShipmentService().Insert(sp);
        }
        if (name2.Value.Trim() != "")
        {

            sp.Commodity = name2.Value;
            sp.HarmonizedCode = "";
            sp.PostTime = DateTime.Now;
            sp.Qty = new Tools().StringToIntDif(num2.Value);
            sp.UnitValue = 0;
            sp.ValueForCustoms = new Tools().StringToDecimalDif(price2.Value);

            new ShipmentService().Insert(sp);
        }


    }
    #endregion
	
    //写入数据
    void ToInsert()
    {


        #region   发送人基本属性
          if (creaduser.Value.Trim() == "847")
        {
		     Jscript.AlertAndGoBack("请选择帐号归属！");
            return;
		 }

        if (creaduser.Value.Trim() != "847")
        {
            if (new UserService().IsQF(creaduser.Value.Trim()))
            {
                Tools.OpenWindow(this, "当前客户欠费已经超过上限！不允许制单", "Default.aspx");
                return;
            }
        }

        Hashtable hs = new Hashtable();
        hs.Add("Sender", sendertxt.Value);
        hs.Add("FromFaxNo", "");
        hs.Add("FromPhoneNo", phonenotxt.Value);
        hs.Add("FromCompany", companytxt.Value);
        hs.Add("FromAddress", addtxt.Value);
        hs.Add("FromCity", "");
        hs.Add("FromState", "");

        hs.Add("FromZIPCode", "");
        #endregion
        #region   收件人基本属性

        hs.Add("Receiver", renametxt.Value);
        hs.Add("ToPhoneNo", rephonenotxt.Value);
        hs.Add("ToCompany", recompanytxt.Value);
        hs.Add("ToAddress", readdtxt.Value.Trim());
		
	    hs.Add("namepy", namepy.Value);
		 hs.Add("admin", Session["username"].ToString());
	    hs.Add("companynamepy", companynamepy.Value);
	    hs.Add("website", website.Value);
	    hs.Add("tozipcode", tozipcode.Value);
        hs.Add("ToCity", "");
        hs.Add("ToState", "");
        hs.Add("ToCountry", "");

		
        #endregion
        #region 其他相关属性
        hs.Add("FlightNo", FlightNotxt.Value);//参考
        hs.Add("AerialNo", AerialNotxt.Value);//航空单号
        hs.Add("CreateUserID", creaduser.Value);
        hs.Add("Origin", qyd_ddr.SelectedItem.Text);
        hs.Add("Destination", mdd_ddr.SelectedItem.Text);
        //支付方式
        hs.Add("Payment", paylist.SelectedItem.Value);
        hs.Add("FromCountry", "");
        hs.Add("Sep", 0);
        //包装形式

        hs.Add("Packing", huowulist.SelectedItem.Value);

        hs.Add("DestPaidBy", 0);

        //保价费








        hs.Add("ShipmentInsurance", 0);

        hs.Add("InsurancePrice", 0);


        hs.Add("InsuredValue", 0);

        //账号：
        string ann = "";
        if (createaccnord.SelectedValue.Trim() == "1")
        {
            //收共
            if (accno_txt.Value.Trim() == ""  )
            {
                Tools.OpenWindow(this, "请输入账号");
                return;
            }
            ann = accno_txt.Value;

			

        }
        else
        {
     
            ann = BillPublic.GetNowTno();


        }
        hs.Add("TrackingNo", ann);


        hs.Add("AccountNo", anccnum.Value);


        hs.Add("FromACENo", "");
        #endregion
        #region 质量 体积
        hs.Add("NoOfPiece", 1); //默认1 有分单  按照分单数计算
        hs.Add("TotalWeight", tool.StringToDecimalDif(StrHelper.VldNull(zhongliang_txt.Value)));//重重量
        hs.Add("DimensionsH", tool.StringToDecimalDif(StrHelper.VldNull(gaotxt.Value)));
        hs.Add("DimensionsL", tool.StringToDecimalDif(StrHelper.VldNull(changtxt.Value)));
        hs.Add("DimensionsW", tool.StringToDecimalDif(StrHelper.VldNull(kuantxt.Value)));

        hs.Add("DimensionsStyle", 0);

        hs.Add("DimensionsWeight", tool.StringToDecimalDif(StrHelper.VldNull(tijizhonglianghd.Value)));

        #endregion
        #region  价格
        hs.Add("ChargedWt", tool.StringToDecimalDif(StrHelper.VldNull(shoufeizhonglianghd.Value)));//收费重量
        hs.Add("SepChargedWt", tool.StringToDecimalDif(StrHelper.VldNull(shoufeizhonglianghd.Value)));//收费重量
        // hs.Add("DeclarePrice", (tool.StringToDecimalDif(StrHelper.VldNull(allprice.Text.Trim())) > PirceSum * PriceRate) ? PirceSum * PriceRate : tool.StringToDecimalDif(StrHelper.VldNull(allprice.Text.Trim())));
        hs.Add("FreightCharge", tool.StringToDecimalDif(zlshoufeihd.Value));//重量收费
        hs.Add("DeclarePrice", tool.StringToDecimalDif(haiguanhd.Value));//海关申报总价
        hs.Add("Memo2", tool.StringToDecimalDif(dianfufeilb.Value));//垫付费

        string sv = jifeitype.SelectedItem.Value.Trim();


        hs.Add("Memo1", sv.Substring(0, sv.IndexOf(",")));//计费类别
        hs.Add("Memo3", tool.StringToDecimalDif(daigoufeihd.Value));//代购费
        hs.Add("Memo4", tool.StringToDecimalDif(baozhuangfeihd.Value));//包装费
        hs.Add("Duties", tool.StringToDecimalDif(guanshuitxt.Value));//关税
        hs.Add("Premium", tool.StringToDecimalDif(baoxianfeitxt.Value));//保险费
        hs.Add("OtherCharge", tool.StringToDecimalDif(othertxt.Value));//其他费用
        hs.Add("Memo5", tool.StringToDecimalDif(youhuitxt.Value));//优惠
        hs.Add("Total", tool.StringToDecimalDif(Totalhb.Value));//总费用
        hs.Add("SepTotal", tool.StringToDecimalDif(Totalhb.Value));//总费用
        #endregion
        #region  状态
        hs.Add("BankID", 1);
        //    hs.Add("BillState", 1);
        hs.Add("IsPlot", 0);
        hs.Add("StateId", 1);
        hs.Add("Complete", 0);

        hs.Add("BillingCopyDate", DateTime.Now);
        hs.Add("UPEXState", "可编辑");




        if (new PublicSqlService().GetCoun("BID", "Tbl_WayBill", "TrackingNo='" + ann + "'") != 0)
        {

            Tools.OpenWindow(this, "当前单号存在，请重试！" + ann);
            return;
        }
        if (new PublicSqlService().Insert(hs, "Tbl_WayBill"))
        {
            InsertHuowu(ann);//插入货物
			InsertHuowu2(ann);//插入货物
            StateInsert(ann);
            Ly(ann);

            if (Request.QueryString["area"] != null)
            {
                //重用，返回前一页

                if (ViewState["lasturl"] != null && ViewState["lasturl"].ToString() != "")
                {
                    Tools.OpenWindow(this, "制单成功！", ViewState["lasturl"].ToString());
                }
                else
                {
                    Tools.OpenWindow(this, "制单成功！", "BillManaga.aspx");
                }
            }
            else
            {
                Tools.OpenWindow(this, "制单成功！", "BillManaga.aspx");
            }
        }
        else
        {
            Tools.OpenWindow(this, "制单失败！请重试");
            return;
        }
        #endregion



    }
    #region 获取写入编辑
    private void InsertHuowu(string acc)
    {
        if (Request.QueryString["area"] == null)
        {
            //写入


            Shipment sp = new Shipment();
            sp.Commodity = name1.Value;
            sp.TrackingNo = acc;
            if (sp.Commodity.Trim() != "")
            {
                sp.HarmonizedCode = "";
                sp.PostTime = DateTime.Now;
                sp.Qty = new Tools().StringToIntDif(num1.Value);
                sp.UnitValue = 0;
                sp.ValueForCustoms = new Tools().StringToDecimalDif(price1.Value);

                new ShipmentService().Insert(sp);
            }
            if (name2.Value.Trim() != "")
            {

                sp.Commodity = name2.Value;
                sp.HarmonizedCode = "";
                sp.PostTime = DateTime.Now;
                sp.Qty = new Tools().StringToIntDif(num2.Value);
                sp.UnitValue = 0;
                sp.ValueForCustoms = new Tools().StringToDecimalDif(price2.Value);

                new ShipmentService().Insert(sp);
            }

        }
        else
        {
            //编辑
        }

    }
    #endregion
    #region 状态写入
    private void StateInsert(string Tno)
    {
        string state = stateidhd.Value.Trim();

        //  DAL.SysTemError.SystemLog(statenamehd.Value);
        string[] idlist = state.Split(',');
        string[] statenamelist = statenamehd.Value.Trim().Split(',');
        string[] datelist = datehd.Value.Trim().Split(',');
        string[] gongsilist = gongsihd.Value.Trim().Split(',');
        string[] danhaolist = danhaohd.Value.Trim().Split(',');

        string[] beizhu = beizhuhd.Value.Trim().Split(',');
        string id = "";
        string name = "";

        Hashtable hs = new Hashtable();

        int ok = 0;
        for (int i = 0; i < idlist.Length; i++)
        {


            if (idlist[i].ToString().Trim() != "")
            {


                hs.Clear();
                hs.Add("SepNo", Tno);
                hs.Add("Date", tool.StringToTime(datelist[i].ToString()));
                hs.Add("StateID", idlist[i].ToString());
                hs.Add("RecordDate", DateTime.Now);
                hs.Add("RecorderID", Session["uid"].ToString());
                hs.Add("CompanyID", tool.StringToIntDif(gongsilist[i]));
                hs.Add("CompanyNo", danhaolist[i]);
                hs.Add("Remark", beizhu[i]);



                if (new PublicSqlService().Insert(hs, "Tbl_BillStateRec"))
                {
                    id = idlist[i].ToString();
                    name = statenamelist[i].ToString();
                    //写入成功
                    ok++;
                    //     DAL.SysTemError.SystemLog(ok.ToString());
                }

            }


        }
        if (ok > 0)
        {
            //写入成功过。更新总单据状态

            hs.Clear();

            hs.Add("StateId", id);
            hs.Add("UPEXState", name);

            new PublicSqlService().Update(hs, "Tbl_WayBill", "TrackingNo='" + Tno + "'");
            // DAL.SysTemError.SystemLog("更新了主单");
        }
        else
        {
            //录入默认状态
            hs.Clear();
            hs.Add("SepNo", Tno);
            hs.Add("Date", DateTime.Now);
            hs.Add("StateID", 1);
            hs.Add("RecordDate", DateTime.Now);
            hs.Add("RecorderID", Session["uid"].ToString());
            hs.Add("CompanyID", 0);
            hs.Add("CompanyNo", "");
            new PublicSqlService().Insert(hs, "Tbl_BillStateRec");
            //hs.Clear();
            //hs.Add("StateId", 1);
            //hs.Add("UPEXState", "可编辑");
            //new PublicSqlService().Update(hs, "Tbl_WayBill", "TrackingNo='" + Tno + "'");

        }




    }


    #endregion

    private void Ly(string no)
    {

        if (liuyanneirong.Value.Trim() != "")
        {
            Hashtable hs = new Hashtable();
            hs.Add("Tno", no);
            hs.Add("Content", liuyanneirong.Value);
            hs.Add("PostUser", "公司");
            hs.Add("UserIsRead", 0);
            hs.Add("UPEXIsRead", 1);
            hs.Add("PostID", Session["uid"].ToString());
            hs.Add("PostDate", DateTime.Now);

            UploadFile up = new UploadFile("jpg,gif,bmp,doc,xls", 1000, "\\Temp\\");
            string att = "";

            if (imageup.FileName.Trim() != "")
            {
                if (up.UpLoad(imageup))
                {
                    att = up.FileName;
                }
            }
            hs.Add("Attachment ", att);
            new PublicSqlService().Insert(hs, "Tbl_Discuss");
        }

    }
    protected void Okbtn_Click(object sender, ImageClickEventArgs e)
    {


        ToInsert();
    }
}
